package com.zhoutao123.hephaestus.service.impl;

import com.zhoutao123.hephaestus.config.CacheKey;
import com.zhoutao123.hephaestus.object.bussiness.VMenu;
import com.zhoutao123.hephaestus.repository.entity.Menu;
import com.zhoutao123.hephaestus.repository.entity.MenuExample;
import com.zhoutao123.hephaestus.service.AbstractService;
import com.zhoutao123.hephaestus.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MenuServiceImpl extends AbstractService implements MenuService {
  @Override
  @Cacheable(CacheKey.MENU_KEY)
  public List<VMenu> getList() {
    MenuExample parentExample = new MenuExample();
    parentExample.createCriteria().andPidIsNull();
    List<Menu> parentMenu = menuMapper.selectByExample(parentExample);
    List<VMenu> vMenuList =
        parentMenu
            .stream()
            .map(VMenu::of)
            .map(
                vMenu -> {
                  return vMenu.setSubMenuList(getSubMenuList(vMenu.getId()));
                })
            .collect(Collectors.toList());
    return vMenuList;
  }

  private List<VMenu> getSubMenuList(String parentMenuId) {
    MenuExample subMenuExample = new MenuExample();
    subMenuExample.createCriteria().andPidEqualTo(parentMenuId);
    List<Menu> menus = menuMapper.selectByExample(subMenuExample);
    return menus.stream().map(VMenu::of).collect(Collectors.toList());
  }

  @Override
  public VMenu add() {
    return null;
  }
}
